﻿#ifndef CUSTOMSPINBOX_H
#define CUSTOMSPINBOX_H
#include <QSpinBox>
#include <QFrame>
#include <QPushButton>
#include <QLineEdit>
#include <QHBoxLayout>
#include "styleDefine.h"

class CustomSpinBoxInt : public QFrame
{
    Q_OBJECT
public:
    CustomSpinBoxInt(QWidget* parent = nullptr)
        : QFrame(parent)
        , m_pIncrease(nullptr)
        , m_pDecrease(nullptr)
        , m_pSpinBox(nullptr)
        , m_nMaximum(INVALID_VALUE), m_nMinimum(INVALID_VALUE) {
        QHBoxLayout* pLayout = new QHBoxLayout;
        pLayout->setSpacing(0);
        pLayout->setContentsMargins(0, 0, 0, 0);
        this->setLayout(pLayout);
        m_pIncrease = new QPushButton(this);
        m_pDecrease = new QPushButton(this);
        m_pSpinBox = new QLineEdit(this);
        m_pSpinBox->setAlignment(Qt::AlignHCenter);
        m_pSpinBox->setText("0");
        m_pSpinBox->setFont(gFontConsolas);

        pLayout->addWidget(m_pDecrease);
        pLayout->addWidget(m_pSpinBox);
        pLayout->addWidget(m_pIncrease);
        connect(m_pIncrease, SIGNAL(clicked()), this, SLOT(slt_Increase()));
        connect(m_pDecrease, SIGNAL(clicked()), this, SLOT(slt_Decrease()));

        m_pDecrease->setStyleSheet("QPushButton { border: none; background-color: transparent; }");
        m_pIncrease->setStyleSheet("QPushButton { border: none; background-color: transparent; }");
        m_pDecrease->setIcon(QIcon(":/common/resource/common/decrease.ico"));
        m_pIncrease->setIcon(QIcon(":/common/resource/common/increase.ico"));
    }

    virtual ~CustomSpinBoxInt() {}
    void setRange(const uint nMin, const uint nMax) {
        m_nMinimum = nMin;
        m_nMaximum = nMax;
    }
    void setDefeat(const uint nValue){
        m_pSpinBox->setText(QString::number(nValue));
    }
    uint getCurValue() {
        return m_pSpinBox->text().toInt();
    }
private slots:
    void slt_Increase() {
        uint nCur = getCurValue();
        if ((INVALID_VALUE != m_nMaximum && nCur < m_nMaximum) || INVALID_VALUE == m_nMaximum)
        {
            m_pSpinBox->setText(QString::number(nCur + 1));
        }
    }
    void slt_Decrease() {
        uint nCur = getCurValue();
        if ((INVALID_VALUE != m_nMinimum && nCur > m_nMinimum) || INVALID_VALUE == m_nMinimum)
        {
            m_pSpinBox->setText(QString::number(nCur - 1));
        }
    }

private:
    QPushButton*    m_pIncrease;    // 增大按钮
    QPushButton*    m_pDecrease;    // 减小按钮
    QLineEdit*      m_pSpinBox;     // 数值显示
    uint            m_nMaximum;     // 设置最小值
    uint            m_nMinimum;     // 设置最大值
};

#endif // CUSTOMSPINBOX_H
